import React, { useEffect, useRef } from "react";
import { Card, Typography, Space } from "antd";

const { Title, Paragraph } = Typography;

const MapPage: React.FC = () => {
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<any>(null);

  useEffect(() => {
    // Only run on client side
    if (typeof window === "undefined") {
      return;
    }

    // Dynamically import AMap loader to avoid SSR issues
    const loadMap = async () => {
      try {
        const AMapLoader = (await import("@amap/amap-jsapi-loader")).default;

        const AMap = await AMapLoader.load({
          key: "fb96a278d3a9e4ecc56b6a7abdcc979e", //申请好的 Web 端开发者 Key，首次调用 load 时必填
          version: "1.4.15", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale", "AMap.Driving"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['AMap.Scale','...','...']
        });

        var driving = new AMap.Driving({
          map: mapRef.current,
          panel: "panel",
        });

        // 根据起终点经纬度规划驾车导航路线
        driving.search(
          new AMap.LngLat(116.379028, 39.865042),
          new AMap.LngLat(116.427281, 39.903719),
          function (status: any, result: any) {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            console.log(result, "result");
            if (status === "complete") {
              console.log("绘制驾车路线完成");
            } else {
              console.log("失败");
            }
          }
        );

        if (mapContainerRef.current && !mapRef.current) {
          mapRef.current = new AMap.Map(mapContainerRef.current, {
            resizeEnable: true,
            center: [116.397428, 39.90923], //地图中心点
            zoom: 13, //地图显示的缩放级别
          });
        }
      } catch (error) {
        console.error("Failed to load AMap:", error);
      }
    };

    loadMap();

    // Cleanup function
    return () => {
      if (mapRef.current) {
        mapRef.current.destroy();
        mapRef.current = null;
      }
    };
  }, []);

  return (
    <div style={{ padding: "24px" }}>
      <div
        ref={mapContainerRef}
        style={{ width: "100%", height: "500px", marginTop: "16px" }}
      />

      <Card>
        <Space direction="vertical" size="large" style={{ width: "100%" }}>
          <Title level={2}>地图页面</Title>

          <Paragraph>
            这是一个地图页面的示例。你可以在这里集成地图组件，比如：
          </Paragraph>

          <ul>
            <li>Google Maps</li>
            <li>百度地图</li>
            <li>高德地图</li>
            <li>Leaflet</li>
            <li>Mapbox</li>
          </ul>

          <Paragraph>
            当前页面路径: <code>/map</code>
          </Paragraph>
        </Space>
      </Card>
    </div>
  );
};

export default MapPage;
